<template>
  <section class="todoapp">
    <TOdoHeader @add="addFn" :arr="list"></TOdoHeader>
    <TOdoMain :arr="showList" @del="delFn"></TOdoMain>
    <TOdoFooter
      :arr="list"
      @changeType="changeTypeFn"
      @clearDone="clearDoneFn"
    ></TOdoFooter>
  </section>
</template>

<script>
// 样式引入 + 导入组件并注册使用
import TOdoHeader from "./components/TodoHeader.vue";
import TOdoMain from "./components/TodoMain.vue";
import TOdoFooter from "./components/TodoFooter.vue";

// 引入css样式
import "./styles/base.css";
import "./styles/index.css";
export default {
  data() {
    return {
      type: "all",
      list: JSON.parse(localStorage.getItem("todoList")) || [],
    };
  },
  components: {
    TOdoHeader,
    TOdoMain,
    TOdoFooter,
  },
  methods: {
    // 添加任务
    addFn(name) {
      this.list.unshift({
        id: +new Date(),
        name,
        isDone: false,
      });
    },
    // 删除任务
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 删除已完成的
    clearDoneFn() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    changeTypeFn(type) {
      this.type = type;
    },
  },
  computed: {
    showList() {
      if (this.type === "active") {
        // 计算未完成的任务
        return this.list.filter((item) => !item.isDone);
      } else if (this.type === "complete") {
        // 计算已完成的任务
        return this.list.filter((item) => item.isDone);
      } else {
        // 所有的数据
        return this.list;
      }
    },
  },
  // 本地缓存
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.list));
      },
    },
  },
};
</script>
